package com.springboot.astra.controller;

import com.springboot.astra.bean.Shopcart;
import com.springboot.astra.result.DataResult;
import com.springboot.astra.service.ShopcartService;
import com.springboot.astra.util.DateUtils;
import com.springboot.astra.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/cart")
public class ShopCartController {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    ShopcartService shopcartService;
    @PostMapping("/addOneGoods")
    @Transactional
    public DataResult addOneGoods(@RequestParam Map<String,String> map, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtils.parseJwt(token);
        Integer userId = Integer.valueOf(claims.getId());
        Integer goodsId = Integer.valueOf(map.get("goodsId"));
        Shopcart shopcart = new Shopcart();
        shopcart.setUserId(userId);
        shopcart.setGoodsId(goodsId);
        shopcart.setGoodsCount(1);
        shopcart.setCreateTime(DateUtils.getTime());
        shopcart.setUpdateTime(DateUtils.getTime());
        shopcart.setDelete(true);
        shopcartService.insertOne(shopcart);
        return DataResult.success();
    }
    @PostMapping("/deleteOneGoods")
    public DataResult deleteOneGoods(@RequestParam Map<String,String> map) {
        Integer shopCartId = Integer.valueOf(map.get("shopCartId"));
        shopcartService.deleteOneById(shopCartId);
        return DataResult.success();
    }
    @GetMapping("/getAll")
    public DataResult getAll(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtils.parseJwt(token);
        Integer userId = Integer.valueOf(claims.getId());
        List<Shopcart> shopcartList = shopcartService.getAllByUserId(userId);
        return DataResult.success(shopcartList);
    }
}
